iT邦幫忙

0

Day 2: 9. Palindrome Number

  • 分享至 

  • xImage
  •  

Given an integer x, return true if x is a palindrome, and false otherwise.
Example 1:
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
解題思路
要判斷數字是否正反讀一樣,但不能用字串,所以要用數學方式反轉。
1.避免多餘反轉:
不需要整個數字反轉,只要反轉一半即可!
例如:
1221→反轉一半得到12,與剩下的12比較
12321→反轉後半得到123,與前半12比較(去掉中間數字即可)
2.反轉邏輯:
每次取出最後一位數digit=x%10。
將它加到反轉結果中:reversed=reversed*10+digit。
再將原數去掉最後一位:x=x/10。
當反轉的部分reversed≥原剩下的x時,就代表反轉到一半了。
3.處理特殊情況:
若x < 0:負號不可能對稱→false
若結尾是0(但 x ≠ 0),例如10,反轉後變成01,不可能回文→false
4.比較:
若數字長度為偶數:x == reversed
若為奇數:x == reversed/10
https://ithelp.ithome.com.tw/upload/images/20251011/20179424fpA4bU647h.png


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言